package com.atguigu.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class process {
    private int flag = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition condition1 = lock.newCondition();
    private final Condition condition2 = lock.newCondition();
    private final Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 1) {
                condition1.await();
            }
            //干活
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "=" + i);
            }
            //通知
            flag=2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 2) {
                condition1.await();
            }
            //干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "=" + i);
            }
            //通知
            flag=3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 3) {
                condition1.await();
            }
            //干活
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "=" + i);
            }
            //通知
            flag=1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}

public class ThreadOrderAccess {
    public static void main(String[] args) {
        process p = new process();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.print5();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
                , "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.print10();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
                , "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.print15();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
                , "C").start();
    }
}
